import java.applet.*;
import java.awt.*;
import java.util.*;
import java.lang.*;
import java.text.*;
import java.awt.event.*; 
import java.io.*;
import net.sf.saxon.*;
import javax.xml.transform.*;

/**
* Class that makes some tools available to the JScript-code, that 
* can't be done in JScript. Like writing files and doing XSLT2-processing.
*/ 
public class ToolApplet extends Applet implements ActionListener {
	Button openButton;
	/** The xslt2 processor */
	Transform xsltproc;
	/** base directory of application, set to parent of application-directory */
	String baseDir;
	public ToolApplet() {
		Panel p = new Panel();
		openButton = new Button("Open");
		openButton.addActionListener(this);
		p.add(openButton);
		this.add(p);

		xsltproc = new Transform();
		xsltproc.now();
	}
  public void start() {
		java.net.URL url = getCodeBase();
		baseDir = (new File(this.getCodeBase().getPath())).getParentFile().getPath().replaceAll("\\\\","\\/")+'/';
		this.add(new Label('-'+baseDir+'-'))	;
		//transformEBSchema("schemas/PurchaseOrder.xsd");
		try { 
    Object[] args = { this };
    netscape.javascript.JSObject.getWindow(this).call("appletLoaded", args );
		} catch(Exception e) {} // to make testing inside appletviewer possible.
  }
  /** Takes a schemaName and using the ebform-XSLT-processor to 
  * create xhtml with xforms to create an instance of that schema. 
  * @param ebschema The Name of the schema to make a message of. 
  * @return The string with the xhtml of the xform.
  */
  public String transformEBSchema(String ebschema) {
    final StringWriter res = new StringWriter();
    final String febschema = ebschema;
  	java.security.AccessController.doPrivileged(new java.security.PrivilegedAction<String>() {
      public String run() {
		  	try {
		  		StandardURIResolver urir = new StandardURIResolver(new net.sf.saxon.Configuration());
		  		TransformerFactoryImpl tfi = new TransformerFactoryImpl();
		  		Source fxsl = (Source) urir.resolve("stylesheets/Message.xsl", baseDir);
			  	Controller xsl = (Controller) tfi.newTransformer(fxsl);
			  	Source xsd = (Source) xsltproc.loadDocuments(
			  	 baseDir + febschema,
			  	 false, null, false);
			  	javax.xml.transform.stream.StreamResult resr = new javax.xml.transform.stream.StreamResult(res);
			  	xsl.transform(xsd, resr);
			  	
		  	} catch (TransformerException e) {
		  		System.out.println(e.getCause() );
		  	  throw new Error(e);	
		  	}
      	return "";
      }
  	});
  	return res.toString();
  }

	/**
	* Loads a file from the filesystem. 
	* Any exceptions are return in the return-value, 
	* since ie can't handle java-exceptions (ff can!). 
	* @param fileName Name of file, relative to editor-dir. 
	* @return contents of file. 
	* @throws Error when trying to get a file outside editor-space. 
	*/
	public String loadFile(String fileName) {
		final StringWriter res = new StringWriter();
		if (fileName.indexOf("..") != -1) 
			throw new Error("tried to load illegal file!"); // keep within base-dir.
		final String filePath = baseDir + fileName;
		// read the annotation file
  	String annotations = java.security.AccessController.doPrivileged(
  	 new java.security.PrivilegedAction<String>() {
      public String run() {
//			File wfile = new File("Annotations"+wfile.separatorChar+fileName+".xml");
				try {
					BufferedReader lfile = new BufferedReader(new FileReader(filePath));
					String ann = "";
					String line;
					while ((line = lfile.readLine()) != null) {
						res.write(line+"\n");
					}
					lfile.close();
					return ann;
				} catch (SecurityException se) {
					System.out.println("Caught a security exception");
					se.printStackTrace();
					return "Exception:SecurityException";
				}
				catch (FileNotFoundException fnf) {
					System.out.println("File not found...");
					return "Exception:FileNotFoundException";
				}
				catch (IOException iox) {
					System.out.println("File read error...");
					iox.printStackTrace();
					return "Exception:IOException";
				} 		
			}
		});
		return res.toString();
	}

	/**
	* Does nog work yet! needs to be wrapped in a java.security.AccessController.doPrivileged
	* Save a file to the filesystem
	*/
	public boolean saveFile(String fileName, String contents){
		if (fileName.indexOf("..") != -1) 
			throw new Error("tried to load illegal file!"); // keep within base-dir.
		final String filePath = baseDir + fileName;
		// save the annotation file
		try {
			PrintWriter sfile = new PrintWriter(new FileWriter(filePath), true);
			sfile.print(contents);
			sfile.close();
			return true;
		}
		catch (SecurityException se) {
			System.out.println("Caught a security exception");
			se.printStackTrace();
		}
		catch (IOException iox) {
			System.out.println("File save error...");
			iox.printStackTrace();
		}
		return false;
	}

	/** @ignore
	* no use for annotation editor. 
	*/
	public void actionPerformed(ActionEvent e) {
		if (e.getActionCommand().equals("Open")) {
			System.out.println("OPEN CLICKED");

			int arrlen = 10000;
			byte[] infile = new byte[arrlen];
			Frame parent = new Frame();
			FileDialog fd = new FileDialog(parent, "Please choose a file:",
			    FileDialog.LOAD);
			fd.setVisible(true);
			String selectedItem = fd.getFile();
			if (selectedItem == null) {
				// no file selected
			} else {
				File ffile = new File( fd.getDirectory() + File.separator +
				                     fd.getFile());
				// read the file
				System.out.println("reading file " + fd.getDirectory() +
				                        File.separator + fd.getFile() );
				try {
					FileInputStream fis = new FileInputStream(ffile); 
					BufferedInputStream bis = new BufferedInputStream(fis);
					DataInputStream dis = new DataInputStream(bis);
					try {
						int filelength = dis.read(infile);
						String filestring = new String(infile, 0,
						                           filelength);
						System.out.println("FILE CONTENT=" + filestring);
					} catch(IOException iox) {
						System.out.println("File read error...");
						iox.printStackTrace();
					}
				} catch (FileNotFoundException fnf) {
					System.out.println("File not found...");
					fnf.printStackTrace();
				}
			}		
			
		}

	}
}


















